package models

import "github.com/astaxie/beego/orm"

type CommentQueryParam struct {
	BaseQueryParam
	CourseName string
}

type Comment struct {
	Id          int     `orm:"column(comment_id)"`
	Course      *Course `orm:"column(course_id);rel(fk)"`
	UserId      int
	Content     string
	CreateAt    int
	Status      int
	IsAnonymous int
	Images      []*CommentImages `orm:"reverse(many)"`
}

func init() {
	orm.RegisterModel(new(Comment))
}

func (u *Comment) TableName() string {
	return CommentTBName()
}

func CommentTBName() string {
	return TableName("comment")
}

func CommentOne(id int) (*Comment, error) {
	o := orm.NewOrm()
	m := Comment{Id: id}
	err := o.Read(&m)
	if err != nil {
		return nil, err
	}
	return &m, nil
}

func CommentPageList(params *CommentQueryParam) ([]*Comment, int64) {
	query := orm.NewOrm().QueryTable(CommentTBName())
	data := make([]*Comment, 0)

	sort := "Id"
	switch params.Sort {
	case "Id":
		sort = "Id"
	}

	if params.Order == "desc" {
		sort = "-" + sort
	}

	total, _ := query.RelatedSel().Count()
	query.OrderBy(sort).Limit(params.Limit, params.Offset).RelatedSel().All(&data)
	return data, total
}
